﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace NfsCommon.Util
{
    public class JSONHelper
    {
        public static string DataTableToJson(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return "null";
            }
            JavaScriptSerializer myJson = new JavaScriptSerializer();

            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                list.Add(result);
            }
          
            return myJson.Serialize(list);
        }
        /// <summary>
        /// 将字符串流转换成指定类型的对象
        /// </summary>
        /// <typeparam name="T">要转换的对象类型<双击查看原图peparam>
        /// <param name="stream">字符串流</param>
        /// <returns>返回转换后的对象</returns>
        public static T ConvertToObject<T>(string stream)
        {
            if (string.IsNullOrEmpty(stream))
                return default(T);

            T ret;

            try
            {
                if (typeof(T) == typeof(DataTable))
                {
                    JsonConverter con = new Newtonsoft.Json.Converters.DataTableConverter();
                    ret = JsonConvert.DeserializeObject<T>(stream, con);
                }
                else
                {
                    ret = JsonConvert.DeserializeObject<T>(stream);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return ret;
        }
    }
}
